package com.ruoyi.web.controller;

import cn.hutool.core.util.IdUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.web.domain.SysUpload;
import com.ruoyi.web.service.SysUploadService;
import com.ruoyi.web.util.UploadFile;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Api(tags = "文件上传控制层")
@RestController
@RequestMapping("/upload")
public class UploadController {

    protected final Logger logger = LoggerFactory.getLogger(UploadController.class);

    private static final long MAX_FILE_SIZE = 4 * 1024 * 1024; // 15MB

    @Value("${manage-addr}")
    private String manageAddr;

    @Autowired
    private SysUploadService sysUploadService;

    /**
     * 单文件
     *
     * @param file
     * @return
     * @throws IOException
     */
    @ApiOperation(value = "单文件上传")
    @PostMapping("upload")
    public AjaxResult upload(@RequestParam("file") MultipartFile file) throws IOException {
        String oldName = new Date().getTime() + file.getOriginalFilename();//获取上传文件的文件名
//        String fileSpace = System.getProperty("user.dir") + File.separator + "FileSpace";
//        String fileSpace = "/home/services/cloudShow" + File.separator + "FileSpace";
//        String fileSpace = "D:\\cloud-show-manage-localUploadFile";
//        String fileSpace = "/Volumes/WorkDisk/ShanDongZhiZao/FileSpace";
        String fileSpace = "/home/services/suqiu/fileSpace";
        File space = new File(fileSpace);
        if (!space.exists() && !space.isDirectory()) {
            logger.info("===========》文件夹不存在");
            space.mkdir();
        }
        String path = fileSpace + File.separator + oldName;
        File newFile = new File(path);
        file.transferTo(newFile);
        //获取到文件大小
        long fileSizeInBytes = file.getSize();
        if (fileSizeInBytes > MAX_FILE_SIZE) {
            //获取出原文件的路径
            String substring = path.substring(0, path.lastIndexOf("/") + 1);
            String finalFinalFile = new Date().getTime() + file.getOriginalFilename();
            path = substring + IdUtil.simpleUUID() + "_" + finalFinalFile;
            compressJPEG(newFile.getAbsolutePath(), path, 0.1f);
        }
        String id = UUID.randomUUID().toString().replaceAll("-", "");
        SysUpload upload = new SysUpload();
        upload.setBaseId(id);
        upload.setBaseUrl(path);
        sysUploadService.save(upload);
//        String  readPath="https://"+manageAddr+"/upload/getIcon/"+id;
        String readPath = "http://" + manageAddr + "/upload/getIcon/" + id;
        return AjaxResult.success(readPath);
    }

    public static void compressJPEG(String inputPath, String outputPath, float quality) throws IOException {
//        File input = new File(inputPath);
//        BufferedImage image = ImageIO.read(input); 舍弃该方法，原因是在处理上传的PNG类型的图片时会产生图片变为红色的问题
        Image src = Toolkit.getDefaultToolkit().getImage(inputPath);
        BufferedImage image = toBufferedImage(src);
        // 设置JPEG压缩质量
        javax.imageio.plugins.jpeg.JPEGImageWriteParam jpegParams = new javax.imageio.plugins.jpeg.JPEGImageWriteParam(null);
        jpegParams.setCompressionMode(javax.imageio.ImageWriteParam.MODE_EXPLICIT);
        jpegParams.setCompressionQuality(quality);
        File output = new File(outputPath);
        // 以JPEG格式保存压缩后的图像
        ImageIO.write(image, "jpeg", output);
    }

    public static BufferedImage toBufferedImage(Image image) {
        if (image instanceof BufferedImage) {
            return (BufferedImage) image;
        }
        // This code ensures that all the pixels in the image are loaded
        image = new ImageIcon(image).getImage();
        BufferedImage bimage = null;
        GraphicsEnvironment ge = GraphicsEnvironment
                .getLocalGraphicsEnvironment();
        try {
            int transparency = Transparency.OPAQUE;
            GraphicsDevice gs = ge.getDefaultScreenDevice();
            GraphicsConfiguration gc = gs.getDefaultConfiguration();
            bimage = gc.createCompatibleImage(image.getWidth(null),
                    image.getHeight(null), transparency);
        } catch (HeadlessException e) {
            // The system does not have a screen
        }
        if (bimage == null) {
            // Create a buffered image using the default color model
            int type = BufferedImage.TYPE_INT_RGB;
            bimage = new BufferedImage(image.getWidth(null),
                    image.getHeight(null), type);
        }
        // Copy image to buffered image
        Graphics g = bimage.createGraphics();
        // Paint the image onto the buffered image
        g.drawImage(image, 0, 0, null);
        g.dispose();
        return bimage;
    }

    @ApiOperation(value = "文档上传")
    @PostMapping("file")
    public AjaxResult doc(@RequestParam("file") MultipartFile file) throws IOException {
        String oldName = new Date().getTime() + file.getOriginalFilename();//获取上传文件的文件名
        String fileName = UploadFile.escapeExprSpecialWord(file.getOriginalFilename());
//        String fileSpace = System.getProperty("user.dir") + File.separator + "FileSpace";
//        String fileSpace = "/home/services/cloudShow" + File.separator + "FileSpace";
//        String fileSpace = "D:\\cloud-show-manage-localUploadFile";
//        String fileSpace = "/Volumes/WorkDisk/ShanDongZhiZao/FileSpace";
        String fileSpace = "/home/services/suqiu/fileSpace";
        File space = new File(fileSpace);
        if (!space .exists() && !space .isDirectory()){
            logger.info("===========》文件夹不存在");
            space .mkdir();
        }
        String path = fileSpace + File.separator + UploadFile.escapeExprSpecialWord(oldName);
        File newFile = new File(path);
        file.transferTo(newFile);
        String id= UUID.randomUUID().toString().replaceAll("-", "");
        SysUpload upload = new SysUpload();
        upload.setBaseId(id);
        upload.setBaseUrl(path);
        sysUploadService.save(upload);
        String readPath = "http://" + manageAddr + "/upload/getIcon/" + id;
        Map map = new HashMap();
        map.put("filePath", readPath);
        map.put("fileName", fileName);
        map.put("downPath", path);
        return AjaxResult.success(map);
    }

    @ApiOperation(value = "根据id查询，显示图片")
    @GetMapping(value = "getIcon/{id}")
    public void getIcon(HttpServletResponse response, @PathVariable("id") String id) {
        SysUpload upload = sysUploadService.getById(id);
        String encode = System.getProperty("file.encoding");//查看文件编码

        String baseUrl = upload.getBaseUrl();
        FileInputStream fis = null;
        if (upload != null) {
            String path = upload.getBaseUrl();
            try {
                File file = new File(path);
                if (! file.exists()) {
                    return;
                }
                fis = new FileInputStream(file);
                final byte[] byt = new byte[1024];
                while (fis.read(byt) > 0) {
                    response.getOutputStream().write(byt);
                }
                response.setStatus(HttpServletResponse.SC_OK);
            } catch (Exception e) {
                logger.error("异常：===》" + e);
            } finally {
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (final IOException e) {
                        fis = null;
                        logger.error("异常：===》" + e);

                    }
                }
                response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
            }
        } else {
            logger.error("未找到对应的文件！！");
        }
    }

    @GetMapping(value = "getUpload")
    public void getUpload(HttpServletResponse response, HttpServletRequest request, String url) {
        UploadFile.downloadPathFile(url, request, response);
    }
}
